﻿using Framework.Entity;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

namespace BridgeShips {
    public class TabSelectObjs : MonoBehaviour {
        // 得到EventSystem组件
        private EventSystem system;
        // 字典：key 物体编号，物体
        private Dictionary<uint, GameObject> m_DcObj;
        // 用于存储得到的字典的索引
        private uint m_uKey;

        private Transform m_ObjTransform;

        //偏移量
 
        public bool m_IsMove;

        void Start() {
            system = EventSystem.current;
            m_DcObj = new Dictionary<uint, GameObject>();
            m_uKey = 0;
        }


        public void GenTableSelectObjects() {
            system = EventSystem.current;
            var entityList = GameEntry.Instance.EntityManager.Entitys();
            if (entityList == null || entityList.Count <= 0)
                return;
            // 给字典赋值

            LinkedListNode<IEntity> node = entityList.First;

            while (node != null) {
                uint id = node.Value.GetID();
                if (!m_DcObj.ContainsKey( id )) {
                    m_DcObj.Add( id, node.Value.Get() );
                }
                m_uKey = id;
                node = node.Next;
            }

            // 得到字典中对应索引的物体
            GameObject obj;
            m_DcObj.TryGetValue( m_uKey, out obj );
            // 设置第一个可交互的UI为高亮状态
            system.SetSelectedGameObject( obj, new BaseEventData( system ) );
        }

        void Update() {
            if (system == null)
                return;
            // 当有 UI 高亮(得到高亮的UI，不为空)并且 按下Tab键
            if (/*system.currentSelectedGameObject != null &&*/ Input.GetKeyDown( KeyCode.Tab )) {
                // 得到当前高亮状态的 UI 物体
                //GameObject hightedObj = system.currentSelectedGameObject;
                // 看是场景中第几个物体

                foreach (KeyValuePair<uint, GameObject> item in m_DcObj) {
                    if (item.Key <= m_uKey) {
                        continue;
                    }
                    else {
                        m_uKey = item.Key;
                        break;
                    }
                }
                // 得到对应索引的游戏物体
                GameObject obj;
                m_DcObj.TryGetValue( m_uKey, out obj );

                // 使得到的物体高亮
                system.SetSelectedGameObject( obj, new BaseEventData( system ) );
                GameController.SimpleCameraControl.SetEnable( m_IsMove );
                if (Input.GetKey( KeyCode.LeftControl )) {
                    m_IsMove = true;
                    m_ObjTransform = obj.transform;
                }
            }

            if (m_IsMove && GameController.SimpleCameraControl) {
                m_IsMove = GameController.SimpleCameraControl.CameraTracePath( m_ObjTransform.position  , m_IsMove );
            }
        }
    }
}